<template>
  <el-upload
    class="ui-pic-upload"
    :action="$http.adornUrl('/v1/file/upload')"
    :headers="{Authorization: $cookie.get('Authorization')}"
    :file-list="fileList"
    :on-remove="handleRemove"
    :on-success="handleUploadSuccess"
    :before-upload="beforeUpload"
    :before-remove="beforeRemove"
    :accept="accept"
    :limit="1"
    :show-file-list="true"
  >
    <img v-if="value" :src="value" class="ui-preview">
    <i v-else class="el-icon-plus ui-uploader-icon"></i>
  </el-upload>
</template>

<script>
/**
 * 单文件上传组件
 */
export default {
  data () {
    return {
      resourcesUrl: window.SITE_CONFIG.resourcesUrl
    }
  },
  props: {
    value: {
      type: String,
      default: '',
    },
    accept: {
      type: String,
      default: '.jpg, .jpeg, .png, .gif'
    }
  },
  computed: {
    fileList () {
      return this.value ? this.value.split(',').map(url => ({
        name: url,
        url: url
      })) : []
    }
  },
  methods: {
    // 数据格式化
    output (fileList) {
      console.log(fileList)
      this.$emit('input', fileList.map(file => {
        // **response.data**
        // fileName: "xxx.txt"
        // fileSize: "4.0B"
        // fileType: "txt"
        // imgUrl: "https://oss.jx9n.cn/image/20210730121631278.txt"
        // type: 2
        return file.response.data.imgUrl
      }).join(','))
    },
    // 限制文件上传大小
    beforeUpload (file) {
      const maxSize = 2
      const isLimit = maxSize * 1024 * 1024 > file.size
      if (!isLimit) {
        this.$message.error(`文件大小不能超过 ${maxSize}MB!`)
      }
      return isLimit
    },
    // 上传
    handleUploadSuccess (response, file, fileList) {
      this.output(fileList)
    },
    // 删除文件
    handleRemove (file, fileList) {
      this.output(fileList)
    },
    // 确认删除
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 文件超出个数限制时的钩子
    handleExceed (files, fileList) {
      this.$message.error('文件已上传')
    },
  }
}
</script>

<style lang="scss" scoped>
$previewSize: 98px;

.ui-pic-upload /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409EFF;
  }
}

.ui-uploader-icon,
.ui-preview {
  width: $previewSize;
  height: $previewSize;
  line-height: $previewSize;
  display: block;
}

.ui-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: $previewSize;
  text-align: center;
}
</style>
